﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Text;
using Common;

public partial class website_admin_product_productinfoeditor : PageBase
{
    string ProductImages = ConfigurationManager.AppSettings["ProductImages"].ToString();

    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Expires = -1;
        PageBegin();


        /// 保存设置
        if (RequestBase.GetFormString("___EVENTTARGET") == "save")
        {
            Save(RequestBase.GetFormString("___EVENTARGUMENT"));
        }

        if (!IsPostBack)
        {
            CategoryDataBind();
            BrandTypeDataBind();
            if (RequestBase.GetQueryString("productid") != "")
                Initialize();

        }
    }

    #region 下来菜单数据绑定

    void BrandTypeDataBind()
    {
        var bindControl = new BindControl();
        bindControl.BindEnumItems_HtmlSelect(selBrand, "brandType", true);
        bindControl.BindEnumItems_HtmlSelect(selCapacity, "Capacity", true);
        bindControl.BindEnumItems_HtmlSelect(selCountry, "Country", true);
        bindControl.BindEnumItems_HtmlSelect(selGrape, "grape", true);
    }

    void CategoryDataBind()
    {
        DataTable dt = BLL.CommonBLL.Select("ProductCategoryBase", "*", " AND DeletionStateCode = 0 ORDER BY LineNum ASC");
        DropdownlistDataBind(1, "00000000-0000-0000-0000-000000000000", dt);
    }
    /// <summary>
    /// 类别列表邦定
    /// </summary>
    /// <param name="intLayer">级别</param>
    /// <param name="parentId">父目录ID</param>
    /// <param name="dt">目录数据表</param>
    void DropdownlistDataBind(int intLayer, string parentId, DataTable dt)
    {
        if (dt == null)
            return;

        DataRow[] dr = dt.Select("Layer = " + intLayer.ToString() + " AND ParentId = '" + parentId + "'");

        ArrayList al = new ArrayList();
        ListItem li;

        string str = ""; int intCategoryLayerID = 0;
        foreach (DataRow d in dr)
        {
            str = "　| ";
            intCategoryLayerID = int.Parse(d["Layer"].ToString());
            if (intLayer == 1)
                str = " + ";
            for (int i = 1; i < intLayer * intLayer; i++)
                str += "--";

            li = new ListItem("\t" + str + "\t" + d["CategoryName"].ToString(), d["CategoryId"].ToString());
            selCategoryList.Items.Add(li);
            DropdownlistDataBind(intCategoryLayerID + 1, d["CategoryId"].ToString().Trim(), dt);
        }
    }
    #endregion

    #region 数据初始化
    void Initialize()
    {
        Model.ProductBase _obj = BLL.ProductBase.GetProductObjById(RequestBase.GetQueryString("productid"));
        ProductObj = _obj;
        AttachmentsObj = BLL.AttachmentsBase.GetAttachments(RequestBase.GetQueryString("productid"));
    }

    Model.ProductBase ProductObj
    {
        get
        {
            Model.ProductBase _product = new Model.ProductBase();

            if (!string.IsNullOrEmpty(RequestBase.GetQueryString("productid")))
                _product.ProductId = RequestBase.GetQueryString("productid");

            _product.ProductName = txtProductName.Value.Trim();
            _product.Description = txtDescripiton.Text.Trim();
            _product.CategoryId = selCategoryList.Value.Trim();

            _product.StockAmount = int.Parse(txtStockAmount.Value.Trim());
            _product.StockStatus = (_product.StockAmount > 0) ? 0 : 1;
            _product.TitlePicture = txtUploadControl_TitleImage.Value.Trim().Replace("|", "");
            _product.ModifiedOn = DateTime.Now;
            _product.CreatedOn = DateTime.Now;
            _product.ModifiedBy = this.SystemUserId;
            _product.CreatedBy = this.SystemUserId;         

            _product.MarketPrice = Convert.ToDecimal(txtPrice.Value.Trim());
            _product.Price = Convert.ToDecimal(txtIntegral.Value.Trim());
            _product.Price2 = Convert.ToDecimal(txtOrderNumber.Value.Trim());
            _product.ProductTypeCode = chkCom.Checked ? 1 : 0;
            _product.Approvals = selGrape.Value.Trim();
            _product.Power = selCapacity.Value.Trim();
            _product.PowerStorageorNot = selBrand.Value.Trim();
            _product.WarrantyInfo = selCountry.Value.Trim();

            return _product;
        }
        set
        {
            if (value != null)
            {
                txtProductName.Value = value.ProductName.Trim();
                txtDescripiton.Text = value.Description;
                selCategoryList.Value = value.CategoryId.Trim();
                txtStockAmount.Value = value.StockAmount.ToString();

                txtPrice.Value = value.MarketPrice.ToString();
                txtIntegral.Value = value.Price.ToString("F0");
                chkCom.Checked = value.ProductTypeCode == 1 ? true : false;
                txtOrderNumber.Value = value.Price2.ToString();
                selCountry.Value = value.WarrantyInfo;
                selCapacity.Value = value.Power;
                selBrand.Value = value.PowerStorageorNot;
                selGrape.Value = value.Approvals;


                if (value.TitlePicture != "")
                {
                    txtUploadControl_TitleImage.Value = "|" + value.TitlePicture.Trim();
                    divTitleImageList_TitleImage.InnerHtml = "<div class=\"attachmentitems\">" + BLL.AttachmentsBase.GetIcoByExtName(value.TitlePicture.Trim().Split('*')[2]) + "&nbsp;&nbsp;<a href='../../" + ProductImages + value.TitlePicture.Trim().Split('*')[1] + "' title='单击打开文件' target='_blank'>" + value.TitlePicture.Trim().Split('*')[0] + "</a>&nbsp;&nbsp; <a href='javascript:void(0);' filedata='" + value.TitlePicture.Trim() + "' itemid='TitleImage' onclick='uploadinit($(this));'>[删除]</a></div>";
                }
            }
        }
    }

    Model.AttachmentsBase[] AttachmentsObj
    {
        get
        {
            if (txtUploadControl_ProductImages.Value.Trim() != "")
            {
                string fileData = "#" + txtUploadControl_ProductImages.Value;
                fileData = fileData.Replace("#|", "");
                string[] arrItems = fileData.Split('|');

                Model.AttachmentsBase[] fileItems = new Model.AttachmentsBase[arrItems.Length];
                int i = 0;
                foreach (string item in arrItems)
                {
                    fileItems[i] = new Model.AttachmentsBase("00000000-0000-0000-0000-000000000000", item.Split('*')[0], item.Split('*')[1], item.Split('*')[2], int.Parse(item.Split('*')[3]), decimal.Parse(item.Split('*')[4]), RequestBase.GetFormString("txtAttachmentFileNotes_" + item.Split('*')[1]), (i + 1).ToString());
                    i++;
                }
                return fileItems;
            }
            else
                return null;
        }
        set
        {
            if (value != null)
            {
                StringBuilder attachments = new StringBuilder();
                string _filedata = "";
                foreach (Model.AttachmentsBase _item in value)
                {
                    _filedata = _item.FileName + "*" + _item.FilePath + "*" + _item.ExtName + "*" + _item.FileType.ToString() + "*" + _item.FileSize.ToString();
                    attachments.Append("<div class=\"attachmentitems\">");
                    attachments.Append(BLL.AttachmentsBase.GetIcoByExtName(_item.ExtName.Trim()));
                    attachments.Append("&nbsp;<a href='../../" + ProductImages + _item.FilePath.Trim());
                    attachments.Append("' title='单击打开文件' target='_blank'>" + _item.FileName.Trim());
                    attachments.Append("</a><br />注释：&nbsp;<input type=\"text\" style=\"width: 320px;\" name=\"txtAttachmentFileNotes_");
                    attachments.Append(_item.FilePath.Trim() + "\" value=\"" + _item.Notes.Trim() + "\" />&nbsp;&nbsp;<a href='javascript:void(0);' filedata='");
                    attachments.Append(_filedata + "' itemid='ProductImages' onclick='uploadinit($(this));'>[删除]</a></div>");
                    txtUploadControl_ProductImages.Value += "|" + _filedata;
                }

                divProductImagesList_ProductImages.InnerHtml = attachments.ToString();
            }
        }
    }
    #endregion

    #region 保存数据
    void Save(string omode)
    {
        string res = "";

        if (RequestBase.GetQueryString("otype").Trim() == "add")
        {
            res = BLL.ProductBase.CreateProduct(ProductObj, AttachmentsObj);
        }

        if (RequestBase.GetQueryString("otype").Trim() == "modify")
        {
            res = BLL.ProductBase.ModifyProduct(ProductObj, AttachmentsObj);
        }

        switch (res.Split('|')[0])
        {
            case "succeeded":
                if (omode == "saveandclose")
                    JScript.AlertAndReturnValueToParent("信息保存成功!", "window.opener.LoadingData();window.close();");
                else
                    JScript.AlertAndReturnValueToParent("信息保存成功!", "window.opener.LoadingData();window.location.href=window.location.href;");
                break;
            default:
                JScript.Alert(res);
                break;
        }
    }
    #endregion
}
